import React, { useState, useEffect } from "react";
import { StyleSheet, View, Text, ScrollView } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import { categories, getAllQuestions } from "@/mocks/questions";
import { useUserStore } from "@/store/user-store";
import { Question } from "@/types/question";
import { useTheme } from "@/hooks/useTheme";
import ProgressBar from "@/components/ProgressBar";
import StatsCard from "@/components/StatsCard";

export default function ProgressScreen() {
  const { answeredQuestions, bookmarkedQuestions, simulations, streakDays } =
    useUserStore();
  const { colors } = useTheme();
  const [allQuestions, setAllQuestions] = useState<Question[]>([]);

  useEffect(() => {
    const loadQuestions = async () => {
      const questions = await getAllQuestions();
      setAllQuestions(questions);
    };
    loadQuestions();
  }, []);

  const answeredCount = Object.keys(answeredQuestions).length;
  const totalQuestions = allQuestions.length;
  const completionRate =
    totalQuestions > 0 ? answeredCount / totalQuestions : 0;
  const averageScore =
    Object.values(answeredQuestions).length > 0
      ? Object.values(answeredQuestions).reduce(
          (sum, answer) => sum + answer.score,
          0
        ) / Object.values(answeredQuestions).length
      : 0;
  const getCategoryProgress = (categoryId: string) => {
    const categoryQuestions = allQuestions.filter(
      (q) => q.category === categoryId
    );
    const answeredCategoryQuestions = Object.values(answeredQuestions).filter(
      (answer) =>
        allQuestions.find((q) => q.id === answer.questionId)?.category ===
        categoryId
    );
    return categoryQuestions.length > 0
      ? answeredCategoryQuestions.length / categoryQuestions.length
      : 0;
  };
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={["bottom"]}>
      <ScrollView showsVerticalScrollIndicator={false}>
        <View style={styles.header}>
          <Text style={[styles.title, { color: colors.text }]}>你的进度</Text>
          <Text style={[styles.subtitle, { color: colors.subtext }]}>追踪你的学习历程</Text>
        </View>
        <View style={styles.statsContainer}>
          <View style={styles.statsRow}>
            <StatsCard
              title="问题"
              value={answeredCount}
              subtitle={`已回答 ${totalQuestions} 题`}
              icon={<Ionicons name="book-outline" size={16} color={colors.primary} />}
            />
            <StatsCard
              title="平均分数"
              value={`${Math.round(averageScore)}%`}
              subtitle="继续提高！"
              icon={<Ionicons name="ribbon-outline" size={16} color={colors.secondary} />}
            />
          </View>
          <View style={styles.statsRow}>
            <StatsCard
              title="连续学习"
              value={streakDays}
              subtitle="天数"
              icon={<Ionicons name="calendar-outline" size={16} color={colors.warning} />}
            />
            <StatsCard
              title="模拟测试"
              value={simulations.length}
              subtitle="已完成"
              icon={<Ionicons name="time-outline" size={16} color={colors.success} />}
            />
          </View>
        </View>
        <View style={[styles.overallProgressCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
          <View style={styles.cardHeader}>
            <Ionicons name="stats-chart" size={20} color={colors.primary} />
            <Text style={[styles.cardTitle, { color: colors.text }]}>总体进度</Text>
          </View>
          <ProgressBar progress={completionRate} showPercentage height={10} />
          <Text style={[styles.progressText, { color: colors.subtext }]}>
            你已回答 {answeredCount} 道题，共 {totalQuestions} 道题
          </Text>
        </View>
        <View style={[styles.categoriesCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
          <Text style={[styles.sectionTitle, { color: colors.text }]}>分类进度</Text>
          {categories.map((category) => (
            <View key={category.id} style={styles.categoryProgress}>
              <View style={styles.categoryHeader}>
                <Text style={[styles.categoryName, { color: colors.text }]}>{category.name}</Text>
                <Text style={[styles.categoryPercentage, { color: colors.primary }]}>
                  {Math.round(getCategoryProgress(category.id) * 100)}%
                </Text>
              </View>
              <ProgressBar
                progress={getCategoryProgress(category.id)}
                height={6}
              />
            </View>
          ))}
        </View>
        <View style={styles.footer} />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  header: {
    marginBottom: 24,
  },
  title: {
    fontSize: 24,
    fontWeight: "700",
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
  },
  statsContainer: {
    marginBottom: 24,
  },
  statsRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 12,
    gap: 12,
  },
  overallProgressCard: {
    borderRadius: 12,
    padding: 16,
    marginBottom: 24,
    borderWidth: 1,
  },
  cardHeader: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 16,
  },
  cardTitle: {
    fontSize: 18,
    fontWeight: "600",
    marginLeft: 8,
  },
  progressText: {
    fontSize: 14,
    marginTop: 8,
  },
  categoriesCard: {
    borderRadius: 12,
    padding: 16,
    marginBottom: 24,
    borderWidth: 1,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "600",
    marginBottom: 16,
  },
  categoryProgress: {
    marginBottom: 16,
  },
  categoryHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 8,
  },
  categoryName: {
    fontSize: 14,
  },
  categoryPercentage: {
    fontSize: 14,
    fontWeight: "600",
  },
  footer: {
    height: 20,
  },
});
